<?php

namespace app\admin\controller;

use app\models\{Business, PlatClass, Goods, GoodsSpec, Region, User as Users, Order, OrderGoods, BussinessLog};
use think\Db;
use think\Validate;

class Shop extends Base
{

    public function users()
    {
        $businessid = $this->request->get('business/d', 0);
        $results = (new Users())->alias('u')
            ->where(['o.status' => 4, 'o.businessid' => $businessid])
            ->distinct(true)
            ->join('order o', 'o.user_id= u.id')->field('u.*');
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        return view(null, [
            'list' => $results
        ]);
    }


    public function businesslog()
    {
        $model = new BussinessLog();
        $data = $this->request->get();
        $results = $model->order('id desc');
        if (!empty($data['id'])) {
            $results = $results->where('user_id', $data['id']);
        }
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        return view(null, [
            'list' => $results
        ]);
    }

    public function shoplist()
    {
        $model = new Business();
        $data = $this->request->get();
        $results = $model->order('id desc');
        if (!empty($data['title'])) {
            $results = $results->where('title|account', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['status'])) {
            $results = $results->where('status', $data['status']);
        }
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            $result['income'] = (new BussinessLog())->where(['user_id' => $result['id'], 'type' => 1])->sum('money') ?? 0;
            $result['goods'] = (new Goods())->where(['businessid' => $result['id'], 'isSale' => 1, 'isdel' => 1])->count();
        }
        return view(null, [
            'list' => $results
        ]);
    }

    public function shoplist_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'remark' => 'require',
                'account' => 'require',
                'status' => 'require',
                'fwtime' => 'require',
                'lat' => 'require',
                'lon' => 'require',
            ], [
                'title.require' => '商家名称不能为空',
                'remark.require' => '商家备注不能为空',
                'account.require' => '商家备注不能为空',
                'status.require' => '商家状态不能为空',
                'fwtime.require' => '服务时间不能为空',
                'lat.require' => '坐标不能为空',
                'lon.require' => '坐标不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (!preg_match("/1[23456789]{1}\d{9}$/", $data['account'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '商户账号请填写可接收验证码的手机号码']);
            }
            $url = 'https://apis.map.qq.com/ws/geocoder/v1';
            try {
                $result = api_curl($url, ['location' => $data['lat'] . ',' . $data['lon'], 'key' => '2AEBZ-YK23W-XISR6-ROOGV-VOLI7-46FFT', 'poi_options' => 'radius=50;policy=5']);
                $data['getaddress'] = $result['result']['formatted_addresses']['recommend'] ?? '';
            } catch (\Exception $e) {
                return json(['code' => 1, 'data' => [], 'msg' =>  $e->getMessage()]);
            }
            $fwtime = explode('-', $data['fwtime']);
            if (count($fwtime) != 2) {
                return json(['code' => 1, 'data' => [], 'msg' => '时间格式错误']);
            }
            if (strtotime($fwtime[0]) > strtotime($fwtime[1])) {
                return json(['code' => 1, 'data' => [], 'msg' => '时间范围错误']);
            }
            if (empty($data['id']) && empty($data['password'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家密码必须填写']);
            }
            if (!empty($data['id']) && empty($data['password'])) {
                unset($data['password']);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            }
            $model = new Business();
            //查找店铺名称、账号是否已经被使用
            $isshop = $model->where('title', $data['title'])->find();
            $haveshop = $model->where('account', $data['account'])->find();
            if (!empty($data['id'])) {
                if (!empty($isshop) && $isshop['id'] != $data['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '店铺名已被使用']);
                }
                if (!empty($haveshop) && $haveshop['id'] != $data['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '店铺账号已被使用']);
                }
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
                if ($res) {
                    return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
                }
                return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
            } else {
                if (!empty($isshop)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '店铺名已被使用']);
                }
                if (!empty($haveshop)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '店铺账号已被使用']);
                }
                Db::startTrans();
                try {
                    $id = $model->allowfield(true)->save($data);
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
                return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
            }
        } else {
            $model = new Business();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            $province = (new Region())->where(['level' => 1])->select();
            $city = [];
            $area = [];
            if (!empty($row['province'])) {
                $city_top = (new Region())->where(['level' => 1, 'name' => $row['province']])->value('id') ?? 0;
                $city = (new Region())->where(['level' => 2, 'parent_id' => $city_top])->select();
            }
            if (!empty($row['city'])) {
                $area_top = (new Region())->where(['level' => 2, 'name' => $row['city']])->value('id') ?? 0;
                $area = (new Region())->where(['level' => 3, 'parent_id' => $area_top])->select();
            }
            return view('', [
                'row' => $row,
                'province' => $province,
                'city' => $city,
                'area' => $area
            ]);
        }
    }

    public function goodslist()
    {
        $model = new Goods();
        $shopmodel = new Business();
        $data = $this->request->get();
        $results = $model->where('isdel', 1)->order('id desc');
        if (!empty($data['title'])) {
            $results = $results->where('title', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['platclassid'])) {
            $results = $results->where('classid', $data['platclassid']);
        }
        if (!empty($data['businessid'])) {
            $results = $results->where('businessid', $data['businessid']);
        }
        if (!empty($data['isSale'])) {
            $results = $results->where('isSale', $data['isSale']);
        }
        if (!empty($data['isnew'])) {
            $results = $results->where('isnew', $data['isnew']);
        }
        if (!empty($data['isSale'])) {
            $results = $results->where('recomm', $data['recomm']);
        }
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        $shop = (new Business())->field('id,title,account')->where('status', 1)->select();
        $platclass = (new PlatClass())->where('isshow', 1)->order(['sort' => 'desc', 'id' => 'desc'])->select();
        foreach ($results as $result) {
            $result['images'] = json_decode($result['images'], true) ?? [];
            $result['shopname'] = $shopmodel->where('id', $result['businessid'])->value('title');
            $result['class_name'] = (new PlatClass())->where('id', $result['classid'])->value('name');
            $result['goodspec'] = (new GoodsSpec())->where(['isdel' => 1, 'goodid' => $result['id']])->order('is_default desc')->find();
        }
        return view(null, [
            'list' => $results,
            'shop' => $shop,
            'platclass' => $platclass
        ]);
    }

    public function goodslist_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'businessid' => 'require',
                'descs' => 'require',
                'images' => 'require',
                'classid' => 'require',
                'spec' => 'require'
            ], [
                'title.require' => '服务名称不能为空',
                'businessid.require' => '商家ID不能为空',
                'descs.require' => '服务描述不能为空',
                'images.require' => '图片不能为空',
                'classid.require' => '平台大类不能为空',
                'spec.require' => '规格必须填写'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (!empty($data['images'])) {
                $data['images'] = json_encode($data['images'], true);
            }
            if (empty($data['spec']) || count($data['spec']) <= 0) {
                return json(['code' => 1, 'data' => [], 'msg' => '规格信息不能少于一个']);
            }
            if (isset($data['file'])) {
                unset($data['file']);
            }
            $shopmodel = new Business();
            $goodmodel = new Goods();
            $specmodel = new GoodsSpec();
            //查找商家是否存
            $shoplist = $shopmodel->where('id', $data['businessid'])->find();
            if (!$shoplist) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家不存在']);
            }
            $data['classid'] = $data['classid'];
            $insert = $data;
            unset($insert['spec']);
            if (empty($data['id'])) {
                Db::startTrans();
                try {
                    $data['id'] = $goodmodel->insertGetid($insert);
                    foreach ($data['spec'] as $spec) {
                        if (!empty($spec['id'])) {
                            $specmodel->where(['goodid' => $data['id'], 'id' => $spec['id']])->update($spec);
                        } else {
                            unset($spec['id']);
                            $spec['businessid'] = $shoplist['id'];
                            $spec['goodid'] =  $data['id'];
                            $specmodel->insert($spec);
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
            } else {
                Db::startTrans();
                try {
                    $goodmodel->where('id', $data['id'])->update($insert);
                    foreach ($data['spec'] as $spec) {
                        if (!empty($spec['id'])) {
                            $specmodel->where(['goodid' => $data['id'], 'id' => $spec['id']])->update($spec);
                        } else {
                            unset($spec['id']);
                            $spec['businessid'] = $shoplist['id'];
                            $spec['goodid'] =  $data['id'];
                            $specmodel->insert($spec);
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
            }
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        } else {
            $model = new Goods();
            $specmodel = new GoodsSpec();
            $shopmodel = new Business();
            $cate = [];
            $id = $this->request->get('id/d', 0);
            $results = $model->where('id', $id)->find();
            $platsons = [];
            $shoplist = $shopmodel->field('id,title,account')->select();
            if ($results) {
                $results['images'] = json_decode($results['images'], true) ?? [];
                $results['speclist'] = $specmodel->order('is_default desc')->where(['businessid' => $results['businessid'], 'isdel' => 1, 'goodid' => $results['id']])->select();
            } else {
                $results['businessid'] = $this->request->get('businessid/d', 0);
            }

            $platclass = (new PlatClass())->where('isshow', 1)->select();
            return view(null, [
                'row' => $results,
                'shoplist' => $shoplist,
                'platclass' => $platclass
            ]);
        }
    }

    public function goodslist_del()
    {
        $id = trim(input('id'), ',');
        $model = new Goods();
        $res = $model->where(['id' => $id])->update(['isdel' => 2]);
        if ($res) {
            return json(['code' => 0, 'status' => 0, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
    }

    public function goodsspec_del()
    {
        $id = trim(input('id'), ',');
        $model = new GoodsSpec();
        $goodsspec = $model->where(['id' => $id, 'isdel' => 1])->find();
        if (empty($goodsspec)) {
            return json(['code' => 1, 'data' => [], 'msg' => '库存规格不存在']);
        }
        //查询规格商品是否超过1个
        $havespec = $model->where(['goodid' => $goodsspec['goodid'], 'isdel' => 1])->count();
        if ($havespec <= 1) {
            return json(['code' => 1, 'data' => [], 'msg' => '库存规格必须保留一个']);
        }
        $res = $model->where(['id' => $id])->update(['isdel' => 2]);
        if ($res) {
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
    }
}